package com.juli.school.service.impl;

import java.util.List;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import com.google.common.collect.Lists;
import com.juli.school.dao.entity.Rec;
import com.juli.school.dao.entity.Stu;
import com.juli.school.dao.mapper.HonorMapper;
import com.juli.school.dao.mapper.RecMapper;
import com.juli.school.dao.mapper.SchoolMapper;
import com.juli.school.dao.mapper.StuMapper;
import com.juli.school.service.bo.RecBo;
import com.juli.school.service.utils.BeanUtils;
import com.juli.school.utils.core.model.CommonResp;
import com.juli.school.utils.log.annotation.DigestLog;
import com.juli.school.utils.self.DateTimeUtils;

@Service
public class RecService {
	
	private static final Logger logger = LoggerFactory.getLogger(RecService.class);
	
	@Resource
	RecMapper recMapper;
	
	@Resource
	StuMapper stuMapper;
	
	@Resource
	SchoolMapper schoolMapper;
	
	@Resource
	HonorMapper honorMapper;
	
	@DigestLog
	public CommonResp<Boolean> add(RecBo recBo) {
		CommonResp<Boolean> commonResp = new CommonResp<Boolean>();
		try {
			recBo.setRecTime(DateTimeUtils.getNow());
			recMapper.insert(recBo);
			commonResp.success();
		} catch (Exception e) {
			logger.error("保存留言信息失败", e);
			commonResp.exception("保存留言信息失败");
		}
		return commonResp;
	}
	
	/**
	 * @Description: 获取发布号为 snStamp 的所有回复内容
	 * @author gaoxiang
	 * @date 2017年10月2日 下午10:52:06
	 */
	public CommonResp<List<RecBo>> list(String snStamp) {
		CommonResp<List<RecBo>> commonResp = new CommonResp<List<RecBo>>();
		Rec rec = new Rec();
		try {
			rec.setSnStamp(snStamp);
			rec.setType(1);
			List<RecBo> recList = fillRecBo(rec,null);
			for(RecBo recBo : recList) {
				Rec rec2 = new Rec();
				rec2.setToId(recBo.getId());
				rec2.setType(2);
				recBo.setRecList(fillRecBo(rec2,recBo.getNick()));
			}
			commonResp.setData(recList);
			commonResp.success();
		} catch (Exception e) {
			logger.error("获取留言信息失败", e);
			commonResp.exception("获取留言信息失败");
		}
		return commonResp;
	}
	
	/**
	 * @Description: 填充回复的元素
	 * @author gaoxiang
	 * @date 2017年10月2日 下午10:51:22
	 */
	private List<RecBo> fillRecBo(Rec rec,String toNick) {
		List<Rec> list = recMapper.list(rec);
		List<RecBo> data = Lists.newArrayListWithCapacity(list.size());
		for (Rec recTemp : list) {
			RecBo recBo = new RecBo();
			BeanUtils.copyProperties(recBo, recTemp);
			Stu stu = stuMapper.getById(Integer.valueOf(recTemp.getStuId()));// 获取查看者学生信息
			recBo.setHeadUrl(stu.getHeadUrl());
			recBo.setNick(stu.getNick());// 回复人昵称
			recBo.setToNick(toNick);// 被回复人昵称
			List<String> honor = honorMapper.getStuIdAll(String.valueOf(recTemp.getStuId()));// 查询该学生荣誉
			recBo.setHonor(honor);
			data.add(recBo);
		}
		return data;
	}
}
